<template>
  <div v-if="display">
    <div class="main-tabs my_tabs" style="position: relative" id="pointBox">
      <!-- <el-tabs tabPosition="left" class="el_point" @tab-click="handleClick">
        <el-tab-pane v-for="item in pointList" :key="item.id">
          <span slot="label">{{ item.name }}</span>
        </el-tab-pane>
      </el-tabs> -->
      <TabPoint :pointList="pointList"></TabPoint>
      <div style="width: 100%">
        <el-form
          :model="transportForm"
          :rules="rules"
          size="mini"
          :label-position="labelPosition"
          ref="ruleForm"
          label-width="80px"
          class="demo-ruleForm"
        >
          <div id="option">
            <div class="title-option">选项</div>
            <el-form-item label="名称" prop="streamName">
              <el-input
                key="streamName"
                v-model="transportForm.streamName"
                placeholder="请输入"
                style="width: 90%"
              ></el-input>
            </el-form-item>

            <div class="title-attribute" id="attribute">属性</div>
            <!-- 拖拽框 -->
            <div class="attributeDrag" id="Drag">
              <draggable
                v-model="nodeAttrList"
                group="people"
                @start="drag = true"
                @end="drag = false"
              >
                <div
                  style="margin-top: 5px"
                  v-for="(v, i) in nodeAttrList.slice(
                    (pageNo - 1) * pageSize,
                    pageNo * pageSize
                  )"
                  :key="i"
                >
                  <el-input
                    size="mini"
                    v-model="v.name"
                    style="width: 80%"
                    class="input-with-select prepend_box"
                  >
                    <el-select
                      v-model="v.type"
                      slot="prepend"
                      placeholder="请选择"
                      style="
                        appearance: none;
                        -moz-appearance: none;
                        -webkit-appearance: none;
                      "
                    >
                      <el-option
                        v-for="type in selectType"
                        :key="type.id"
                        :label="type.name"
                        :value="type.id"
                      ></el-option>
                    </el-select>
                  </el-input>
                  <!-- 删除按钮 -->
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="拖拽调整顺序"
                    placement="right"
                  >
                    <svg-icon
                      class="draganddrop"
                      icon-class="draganddrop"
                    ></svg-icon>
                  </el-tooltip>
                  <svg-icon
                    class="trash"
                    icon-class="trash"
                    @click="delAttribute(i)"
                  ></svg-icon>
                  <!-- <el-button type="text" size="mini" >删除</el-button> -->
                  <!-- <el-button type="text" size="mini" slot="append" icon="el-icon-delete" style="width:25px" @click="delAttribute(i)"></el-button> -->
                </div>
              </draggable>
            </div>

            <el-pagination
              v-show="nodeAttrList.length !== 0"
              size="mini"
              @size-change="sizeChange"
              @current-change="currentChange"
              :current-page.sync="pageNo"
              :page-sizes="[5, 10]"
              :page-size="pageSize"
              :total="nodeAttrList.length"
              layout="sizes, prev, pager, next"
            >
            </el-pagination>

            <el-form-item label="">
              <el-input
                size="mini"
                v-model="transmit.name"
                style="width: 90%"
                class="input-with-select prepend_box"
                clearable
              >
                <el-select
                  v-model="transmit.type"
                  slot="prepend"
                  placeholder="请选择"
                  value-key
                  @change="getSelectType"
                >
                  <el-option
                    v-for="type in selectType"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  ></el-option>
                </el-select>
                <el-button
                  slot="append"
                  icon="el-icon-plus"
                  style="width: 110px"
                  @click="addAttribute"
                  >添加属性</el-button
                >
              </el-input>
            </el-form-item>
          </div>

          <div id="annotation">
            <div class="text_title">注解</div>

            <el-form-item prop="asyncSwitch">
              <el-checkbox-group v-model="transportForm.asyncSwitch">
                <el-checkbox
                  label="@Async"
                  name="type"
                  @change="asyncClick"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <div class="asyncStyle" v-show="asyncShow">
              <div class="async_item">
                <div class="async_title" for="buffer">缓冲大小</div>
                <el-input
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  class="async_input"
                  id="buffer"
                  v-model="asyncAnnotation.buffer"
                  size="mini"
                ></el-input>
              </div>
              <div class="async_item">
                <div class="async_title" for="work">工作数</div>
                <el-input
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  class="async_input"
                  id="work"
                  v-model="asyncAnnotation.work"
                  size="mini"
                ></el-input>
              </div>
              <div class="async_item">
                <div class="async_title" for="batch">最大批量数</div>
                <el-input
                  onkeyup="value=value.replace(/[^\d]/g,'')"
                  class="async_input"
                  id="batch"
                  v-model="asyncAnnotation.batch"
                  size="mini"
                ></el-input>
              </div>
              <!-- <div class="block"> -->

              <!-- </div> -->

              <!-- <div class="block"> -->

              <!-- </div> -->
            </div>
            <div class="demo-input-suffix">
              <div>
                <div class="text_title" id="notes">自定义注解</div>
                <!-- 自定义选项CustomAnnotation -->
                <custom-annotation
                  :customOptionValue="customOptionValue"
                  :items="treeItems"
                  ref="stream_customAnnotation"
                />
              </div>
              <!-- </el-card> -->
            </div>
          </div>
        </el-form>
      </div>

      <!-- 右侧图标 -->
      <!-- <i class="el-icon-setting" style='font-size:24px;position: absolute;right:3%;top:10px;'></i> -->
    </div>
    <!-- 确认取消公共组件 -->
    <top-operation-button @submit="submit" @handClose="handClose" />
  </div>
</template>
<script>
import draggable from "vuedraggable";
import "@/assets/style/stream.css";
import CustomAnnotation from "../CommonComponents/CustomAnnotation";
import TopOperationButton from "../CommonComponents/TopOperationButton";
import {
  parseTreeJson,
  parseJson,
  reverseJson,
  verificationTree,
} from "@/utils/index";
import { streamKey } from "@/utils/local";
import TabPoint from "@/components/TabPoint";
import { mapGetters } from "vuex";
export default {
  name: "",
  components: {
    draggable,
    CustomAnnotation,
    TopOperationButton,
    TabPoint,
  },
  props: {
    display: {
      type: Boolean,
      default: false,
    },
    nodeDataRight: {
      type: Object,
      default: () => {
        return { treeData: [] };
      },
    },
    keyNumber: { type: Number },
  },
  computed: {
    ...mapGetters(["activeTab"]),
  },
  data() {
    return {
      pointList: [
        {
          name: "选项",
          val: "option",
          id: "option",
        },
        // {
        //   name: "属性",
        //   id: "attribute",
        // },
        {
          name: "注解",
          val: "annotation",
          id: "annotation",
        },
        // {
        //   name: "自定义注解",
        //   id: "notes",
        // },
      ],
      pageNo: 1,
      pageSize: 5,
      totalNum: 0,
      labelPosition: "top",
      paginationShow: false,
      transportForm: {
        streamName: "",
        asyncSwitch: false,
      },
      rules: {
        streamName: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            validator(rule, value, callback) {
              var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;

              if (!reg.test(value)) {
                callback(
                  new Error("属性名称首位必须为字母且不能包含特殊符号和空格")
                );
              } else {
                callback();
              }
            },
          },
        ],
      },
      customAnnotationShow: false,
      customAnnotationSwitch: false,
      asyncSwitch: false,
      asyncShow: false,
      //streamName: "",
      transmit: {
        name: "",
        type: "",
      },
      selectType: [
        { id: "STRING", name: "string" },
        { id: "INT", name: "int" },
        { id: "LONG", name: "long" },
        { id: "FLOAT", name: "float" },
        { id: "DOUBLE", name: "double" },
        { id: "BOOL", name: "bool" },
        { id: "OBJECT", name: "object" },
      ],
      select: "",
      value1: false,
      value2: false,
      asyncAnnotation: {
        buffer: "",
        work: "",
        batch: "",
      },
      annotationAsync: {},
      nodeAttrList: [],
      nodeddList: [{ name: "", type: "" }],
      annotationList: {
        key: "",
        value: "",
        queryContextStartIndex: [],
        queryContextEndIndex: [],
      },
      customOptionValue: [],
      nodeData: {},
      selectName: "",
      bool: "true",
      treeItems: [],
      dataId: "",
    };
  },
  watch: {
    nodeDataRight: {
      handler: function (newData, oldData) {
        // console.info("stream 已打开 watch 观察者--------", newData);
        // this.$refs.stream_customAnnotation.items;
        console.log(newData, "节点");
        if (newData) {
          const { asyncAnnotation, annotationListObjects, id } = newData;
          this.dataId = id;
          //如果asyncAnnotation有值 说明是打开的async
          if (annotationListObjects && annotationListObjects.length !== 0) {
            this.treeItems = reverseJson(annotationListObjects);
            // treeData
            const { name, elements } = annotationListObjects[0];
            if (name == "Async") {
              this.asyncAnnotation = {
                buffer: elements.find((item) => item.key == "buffer.size")
                  .value,
                work: elements.find((item) => item.key == "workers").value,
                batch: elements.find((item) => item.key == "batch.size.max")
                  .value,
              };
              this.asyncShow = true; //打开async输入框
              this.transportForm.asyncSwitch = true;
              this.asyncSwitch = true;
            } else {
              this.asyncAnnotation = {};
              this.asyncShow = false;
              this.asyncSwitch = false;
              this.transportForm.asyncSwitch = false;
            }
          }

          if (Object.keys(newData).length != 0) {
            let tempdata = JSON.parse(JSON.stringify(newData));
            this.nodeData = tempdata; //这里会一直拿到老数据
            if (this.nodeData.attributeList != undefined) {
              this.nodeAttrList = this.nodeData.attributeList; //已选择的属性
            }
            if (this.nodeData.name != undefined) {
              this.transportForm.streamName = this.nodeData.name;
            }
            let annoObjects = this.nodeData.annotationListObjects;
          }
          console.info(" stream 已打开--------");
        }
      },
      immediate: true,
      deep: true,
    },
    keyNumber: {
      handler: function (newData, oldData) {},
      immediate: true,
    },
    nodeAttrList: {
      handler: function (newData, oldData) {},
    },
    // "nodeDataRight.attributeList": {
    //   handler: function (newData, oldData) {
    //     if ("" !== newData && newData != undefined) {
    //       console.info("nodeDataRight.attributeList-------");
    //     }
    //   },
    //   deep: true,
    // },
  },
  mounted() {
    // this.sizeChange()
  },
  methods: {
    addshowPagination() {
      if (this.nodeAttrList != []) {
        this.paginationShow = true;
      }
    },
    delshowPagination() {
      if (this.nodeAttrList.length == "0") {
        this.paginationShow = false;
      }
    },
    sizeChange(val) {
      console.log("val", val);
      this.pageSize = val;
      this.pageNo = 1;
    },
    currentChange(val) {
      console.log("currentChangeval", val);
      this.pageNo = val;
    },
    //获取下拉框label
    getSelectType(val) {
      this.selectName = val
        ? this.selectType.find((ele) => ele.id === val).name
        : "";
      this.transmit.type = this.selectName;
    },
    moreState(tab, event) {
      if (tab == "more") {
        return false;
      }
    },

    // 注解下 @Async显隐
    asyncClick() {
      this.asyncShow = !this.asyncShow;
      this.asyncAnnotation = {};
      // this.asyncAnnotation = this.asyncShow ? {} : null; //打开的话复制空对象,关闭null 方便回显操作
    },
    verification() {
      if (
        this.$store.getters["siddhi/streamKeyIsRepear"]({
          id: this.dataId,
          val: this.transportForm.streamName,
        })
      ) {
        this.$msg("流节点,表格节点,窗口节点名称不能重复!");
        return false;
      }
      var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;
      const { buffer, work, batch } = this.asyncAnnotation;
      const items = this.$refs.stream_customAnnotation.items;
      const isKeyValue = verificationTree(items);
      if (!this.transportForm.streamName) {
        this.$msg("请输入名称!");
        return false;
      }
      if (!this.$regTextName(this.transportForm.streamName)) {
        this.$msg("属性名称首位必须为字母且不能包含特殊符号和空格,请检查!");
        return false;
      }
      if (this.nodeAttrList.length == 0) {
        this.$msg("请添加属性!");
        return false;
      }
      if (this.transportForm.asyncSwitch) {
        if (!buffer) {
          this.$msg("请输入缓冲大小!");
          return false;
        }
        if (!work) {
          this.$msg("请输入工作数!");
          return false;
        }
        if (!batch) {
          this.$msg("请输入最大批量数!");
          return false;
        }
      }
      if (items.length != 0 && isKeyValue.length !== 0) {
        let names = isKeyValue.map((item) => item.label);
        names = names.join(",");
        this.$msg("自定义注释[" + names + "]必须包含键值!");
        return false;
      }
      if (this.nodeAttrList.some((item) => item.name == "")) {
        this.$msg("属性不能有空值!!");
        return false;
      }

      if (this.nodeAttrList.some((item) => !reg.test(item.name))) {
        this.$msg("属性名称首位必须为字母且不能包含特殊符号和空格,请检查!");
        return false;
      }
      return true;
    },
    // 注解下 自定义注解显隐
    AnnotationClick() {
      this.customAnnotationShow = !this.customAnnotationShow;
    },

    // 属性列表添加
    addAttribute() {
      // if(!this.check()){
      //   return
      // }

      if (!this.transmit.name) {
        this.$msg("请输入属性名称");
        return;
      }
      if (!this.transmit.type) {
        this.$msg("请选择属性类型");
        return;
      }
      var reg = /^[a-zA-Z][-_a-zA-Z0-9]{0,5}/;
      if (!reg.test(this.transmit.name)) {
        this.$msg("属性名称首位必须为字母且不能包含特殊符号和空格");
        return;
      }
      const isRepeat = this.nodeAttrList.some(
        (item) => item.name == this.transmit.name
      );
      if (isRepeat) {
        this.$msg("属性名称不能重复");
        return;
      }
      this.nodeAttrList.push(this.transmit);
      this.transmit = {
        name: "",
        type: "",
      };
      this.addshowPagination();
      //添加属性之后 回到第一页
      this.pageNo = 1;
    },

    // 属性列表删除
    delAttribute(i) {
      this.nodeAttrList = this.nodeAttrList.filter((v, index) => index != i);
      this.delshowPagination();
    },
    //关闭-取消
    handClose() {
      this.$emit("handClose");
    },
    submit() {
      //验证一下 async的表单
      if (!this.verification()) {
        return;
      }
      let that = this;
      let target = {};
      target.annotationList = [];
      target.asyncAnnotation = this.asyncAnnotation; //是否async (数据源)
      target.annotationListObjects = [];
      target.treeData = this.$refs.stream_customAnnotation.items; //树形结构的原始数据,回显使用
      let items = this.$refs.stream_customAnnotation.items;
      //注释的树形结构转换
      target.annotationList = parseTreeJson(items);
      //注释的树形结构转换第二种格式
      target.annotationListObjects = parseJson(items);

      // @Async 数据整理
      if (this.asyncShow) {
        // "@Async( buffer.size='256' ,workers='2' ,batch.size.max='5' )"
        const asyncStr = `@Async( buffer.size='${this.asyncAnnotation.buffer}' ,workers='${this.asyncAnnotation.work}' ,batch.size.max='${this.asyncAnnotation.batch}' )`;
        target.annotationList.unshift(asyncStr);
        target.annotationListObjects.unshift({
          elements: [
            {
              key: "buffer.size",
              value: target.asyncAnnotation.buffer,
            },
            {
              key: "workers",
              value: target.asyncAnnotation.work,
            },
            {
              key: "batch.size.max",
              value: target.asyncAnnotation.batch,
            },
          ],
          annotations: [],
          name: "Async",
        });
      } else {
        delete target.asyncAnnotation;
      }
      // Object.assign(target, that.nodeData); //这里不知道做什么的 会覆盖下边asyncAnnotation的数据格式
      target.attributeList = that.nodeAttrList;
      target.name = that.transportForm.streamName;
      target.annotationList = target.annotationList.filter((item) => item);
      let returnData = {
        display: false,
        type: "streamList",
        objectState: this.nodeDataRight.objectState,
        nodeData: target,
        nodeDataRight: this.nodeDataRight,
      };
      this.$emit("returnSource", returnData);
    },
  },
};
</script>
<style lang="scss">
.asyncStyle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
  .async_item {
    display: flex;
    flex-direction: column;
    width: 100%;
    margin-right: 8px;
    .async_title {
      color: #666666;
      font-size: 13px;
    }
    &:last-child {
      margin-right: 0;
    }
  }
  .async_title {
    margin-bottom: 10px;
  }
}
.my_tabs
  .el-form-item.is-required:not(.is-no-asterisk)
  .el-form-item__label-wrap
  > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: "" !important;
}
.my_tabs
  .el-form-item.is-required:not(.is-no-asterisk)
  .el-form-item__label-wrap
  > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:after {
  content: "*";
  color: #f56c6c;
  margin-left: 8px;
}
.my_tabs {
  display: flex;
  height: 80vh;
  overflow-x: hidden;
  .el_point {
    position: sticky;
    top: 0;
    margin-right: 20px;
    overflow: initial;
  }
}
.prepend_box .el-input-group__prepend {
  width: 90px !important;
}
</style>
